<?php

class HRURequestDispatcher extends RequestDispatcher {
	
	/**
	 * @see RequestDispatcher::dispatch()
	 *
	 */
	private function baseInURL($haystack, $needle) {
		if (($pos = strpos ( $haystack, $needle )) === FALSE)
			return FALSE;
		return substr ( $haystack, $pos + strlen ( $needle ) );
	}
	
	public function dispatch() {
		$url = trim ( urldecode ( $_SERVER ['REQUEST_URI'] ) );
		
		if ($url != '') {
			
			$actURI = $this->baseInURL ( $url, Session::getSystemValue ( 'basePath', false ) );
			
			if ($actURI == '') {
				$actURI = '/';
				$retURL = '/';
			}
			
			$retURL = $actURI;
			
			#throws new ActionInvokeException()
			#@deprecated
			//$action = Router::getActionCollObjectByName ( $actURI );
			

			#router delete file
			$package = ConfigReader::getInstance ();
			if ($package == null)
				throw new ConfigException ( 'Config error! Can\t load config.' );
			$action = $package->getAction ( $actURI );
			if ($action == null)
				throw new ActionInvokeException ( 'No such action: <b>' . $actURI . '</b> 404 ' );
			#reouter delete file
			

			#try to parse parameters:
			if ($action != null) {
				$mathces = $action [1];
				$pos = strpos ( $actURI, $mathces [0] );
				if ($pos !== false)
					$url = substr ( $actURI, $pos + strlen ( $mathces [0] ) );
				$this->setAttribute ( 'action', $mathces [0] );
				$retURL = $mathces [0];
				#??  unknown mind: ;delete trails "/"
				if ($url [0] == '/')
					$url = substr ( $url, 1 );
				if ($url [strlen ( $url ) - 1] == '/')
					$url = substr ( $url, 0, strlen ( $url ) - 1 );
				$newStyleParams = split ( '\/', $url );
				$i = 0;
				$key = '';
				foreach ( $newStyleParams as $value ) {
					if ($i ++ == 2) {
						
						$this->setAttribute ( $key, $value );
						$i = 0;
					} else {
						$key = $value;
						$i ++;
					}
				}
			
			}
		
		} else
			$retURL = '/';
		
		return $retURL;
	}
	
	/**
	 * @see RequestDispatcher::getAttribute()
	 *
	 */
	public function getAttribute($key) {
		return $_REQUEST [$key];
	}
	
	public function getAttributes() {
		return $_REQUEST;
	}
	
	public function setAttribute($key, $value) {
		$_REQUEST [$key] = $value;
	}
	
	/**
	 * @see RequestDispatcher::isExist()
	 *
	 * @param unknown_type $key
	 */
	public function isExist($key) {
		return isset ( $_REQUEST [$key] );
	}
	
	public function clear() {
		foreach ( $_GET as $key => $value )
			unset ( $_GET [$key] );
		foreach ( $_POST as $key => $value )
			unset ( $_POST [$key] );
		foreach ( $_REQUEST as $key => $value )
			unset ( $_REQUEST [$key] );
	}

}

?>